package showgo.gui;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import showgo.modell.stueck.Rolle;

public class RollenTableModel extends AbstractTableModel {

    /**
     * 
     */
    private static final long serialVersionUID = 6538800684552594410L;

    private List<Rolle> rollen = new ArrayList<Rolle>();

    // Name, Alter, Geschlecht, Wortzahl im Stueck
    Class<?>[] types = new Class[] { java.lang.String.class,
	    java.lang.Integer.class, java.lang.String.class,
	    java.lang.Integer.class };

    @Override
    public int getColumnCount() {
	return 4;
    }

    public List<Rolle> getRollen() {
	return rollen;
    }

    @Override
    public int getRowCount() {
	return rollen.size();
    }

    @Override
    public Object getValueAt(int row, int column) {
	switch (column) {
	case 0:
	    return rollen.get(row).getRollenName();
	case 1:
	    return rollen.get(row).getAlter();
	case 2:
	    return rollen.get(row).getGeschlecht();
	case 3:
	    return rollen.get(row).getTextMenge();
	default:
	    return "";
	}
    }

    public void setValueAt(Object value, int rowIndex, int columnIndex) {
	Rolle rolle = rollen.get(rowIndex);

	switch (columnIndex) {
	case 0:
	    rolle.setRollenName((String) value);
	    break;
	case 1:
	    rolle.setAlter((Integer) value);
	    break;
	case 2:
	    rolle.setGeschlecht((String) value);
	    break;
	case 3:
	    rolle.setTextMenge((Integer) value);
	    break;
	}
	fireTableCellUpdated(rowIndex, columnIndex);
    }

    @Override
    public String getColumnName(int column) {
	switch (column) {
	case 0:
	    return "Rollenname";
	case 1:
	    return "Alter";
	case 2:
	    return "Geschlecht";
	case 3:
	    return "Textmenge im Stueck";
	default:
	    return "";
	}
    }

    @Override
    public boolean isCellEditable(int row, int column) {
	return false;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
	return types[columnIndex];
    }

    public void addRolle(Rolle r) {
	rollen.add(r);
	fireTableDataChanged();
    }

    public void refresh() {
	fireTableDataChanged();
    }

    public boolean isEmpty() {
	return rollen.isEmpty();
    }

    public Rolle removeRolleAt(int rowIndex) {
	Rolle removedRolle = rollen.remove(rowIndex);
	fireTableDataChanged();
	return removedRolle;
    }

    public void removeRolle(Rolle rolle) {
	rollen.remove(rolle);
	fireTableDataChanged();
    }

    public void replaceRolle(Rolle oldRolle, Rolle newRolle) {
	rollen.set(rollen.indexOf(oldRolle), newRolle);
	fireTableDataChanged();
    }

    public Rolle getRolleAt(int rowIndex) {
	if (rowIndex < rollen.size()) {
	    return rollen.get(rowIndex);
	}
	return null;
    }
}
